/**
 * Created by 云鹏 on 2014/9/11.
 */
var express = require('express');
var router = express.Router();
var model = require('../models/bcdoctor');
var UserDoctor = model.UserDoctor;
var model1 = require('../models/index');
var User = model1.User;
var _ = require('underscore');
var async = require('async');
require('date-utils');
var Page = require('../utils/Page');
var settings = require('../config');
var wechat_util = require('../utils/wechatutil');
var crypto = require('crypto');

router.get('/page', function (req, res) {
    var current_page = req.query.page;
    getUserDoctorPages(current_page, res);
});

router.post('/changedState', function (req, res) {
    var pid = req.body.id;
    var user = new User();
    var userDoctor = new UserDoctor();
    userDoctor.updateUserDoctor(pid, function (err) {
        if (err) {
            res.json({staus: "fail"});
        } else {
            //审核成功后修改本地数据库和微信端用户所属组到医师组
            var openid;

            userDoctor.findUserDoctorByid(pid, function(err, doc) {//根据用户ID查询openid
                if(err){
                    res.json({staus: "fail"});
                } else{
                    userDoctor = doc;
                    openid = userDoctor.wcopenid;
                    user.updateUserGroup(openid, function(err) {//修改users表对应的openid的用户的groupid为医师组的groupid
                        if (err) {
                            res.json({staus: "fail"});
                        }else {
                            var util_tool = new wechat_util();
                            util_tool.getAPI(function(api){

                                api.moveUserToGroup(openid, 101, function(err, result) {//移动微信平台用户所属的组
                                    if(err){
                                        res.json({staus: "fail"});
                                    } else{
                                        //成功后发送消息给微信用户
                                        var sendmsg = "恭喜您通过医生认证，记得每天签到哦，这样才能收到问题 :-)";
                                        api.sendText(openid, sendmsg, function (err, result) {
                                            if (err) debug("send message fail", err);
                                            callback(err, result);
                                        });
                                        res.json({staus: "success"});
                                    }
                                });
                            });
                        }
                    });
                }


            });

        }
    })
});

function getUserDoctorPages(currentpage, res) {
    async.waterfall([function (cb) {
        new UserDoctor().getCount(function (err, count) {
            cb(err, count);
        })
    }], function (err, count) {
        new UserDoctor().findUserDoctor(currentpage, function (err, result) {
            var rs = {};
            var page = new Page();
            page.total_row = count;
            if (result.length != 0)page.total_page = Math.ceil(count / settings.pre_page_row);
            page.current_page = currentpage;
            rs.page = page;
            if (err) {
                res.render('error', {
                    message: '医师资格审核',
                    error: err
                });
            } else {
                var userDoctors = new Array();
                for (var i = 0; i < result.length; i++) {
                    var userDoctor = _.clone(result[i]);
                    userDoctor.fordate = userDoctor.fordate.toFormat('YYYY-MM-DD');
                    userDoctors.push(userDoctor);
                }
                rs.userDoctors = userDoctors;
                res.render('bcdoctor', {
                    title: '医师资格审核',
                    result: rs
                });
            }
        })
    })

}

module.exports = router;